﻿using Sidvall.UI.Dialogs;
using System.Threading;
using System.Threading.Tasks;

namespace Sidvall.UI.Wpf.Dialogs
{
    public partial class XamWebDialog
    {
        #region Public Members

        #region ShowAsync

        public async Task ShowAsync(WebDialogContext context, object owner)
        {
            this.WebControl.InitializeContext(context);
            this.Header = context.Title;
            WindowManager.AddControlToWindow(this, owner);
            await WaitForClose();
        }

        #endregion

        #endregion
        #region Private Members

        ManualResetEvent myManualEvent = new ManualResetEvent(false);

        #region CloseDialog

        private void CloseDialog()
        {
            Sidvall.UI.Wpf.WindowManager.RemoveControlFromWindow(this, this.Parent);
            myManualEvent.Set();
        }

        #endregion
        #region WaitForClose

        private async Task WaitForClose()
        {
            await Task.Run((System.Action)WaitForCloseAction);
        }
        private void WaitForCloseAction()
        {
            myManualEvent.WaitOne();
        }

        #endregion

        #endregion
        #region Events

        #region WebControl_CloseSelected

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        private void WebControl_CloseSelected(object sender, System.EventArgs e)
        {
            CloseDialog();
        }

        #endregion
        #region XamDialogWindow_WindowStateChanged

        private void XamDialogWindow_WindowStateChanged(object sender, Infragistics.Controls.Interactions.WindowStateChangedEventArgs e)
        {
            if (e.NewWindowState == Infragistics.Controls.Interactions.WindowState.Hidden)
            {
                CloseDialog();
            }
        }

        #endregion

        #endregion
        #region Constructors

        public XamWebDialog()
        {
            InitializeComponent();

            Sidvall.UI.Wpf.ControlManager.SetLanguage(this);
        }

        #endregion
    }
}
